import type { FormRules, FormItemRule } from 'naive-ui'
import loginApi from '@/service/api/login'
import { useAppsStore } from '@/stores/modules/app'

export interface ModelType {
  nickname: string | null
  username: string | null
  name: string | null
  phone: string | null
  avatar: string | null
}

export class BaseInfoModel {
  /**
   * 表单数据
   */
  private data: ModelType = {
    nickname: '',
    username: '',
    name: '',
    phone: '',
    avatar: '',
  }
  /**
   * 表单字段的验证规则
   */
  private rules: FormRules = {
    nickname: [
      {
        required: true,
        message: '昵称不能为空',
        trigger: 'blur',
      },
    ],
    username: [
      {
        required: true,
        message: '用户名不能为空',
        trigger: 'blur',
      },
    ],
    name: [
      {
        required: true,
        message: '姓名不能为空',
        trigger: 'blur',
      },
    ],
    phone: [
      {
        required: true,
        message: '手机号不能为空',
        trigger: 'blur',
      },
    ],
  }
  /**
   * 为特定字段添加额外的验证规则
   * @param key - 字段键
   * @param rule - 验证规则
   */
  public addRules(key: string, rule: FormRules | FormItemRule | FormItemRule[]): void {
    this.rules[key] = rule
  }
  /**
   * 获取验证规则
   * @returns 验证规则
   */
  public getRules(): FormRules {
    return this.rules
  }

  /**
   * 获取表单数据
   * @returns 表单数据
   */
  public getData(): ModelType {
    const userStore = useAppsStore()
    this.data.nickname = userStore.userInfo?.nickname || null
    this.data.username = userStore.userInfo?.username || null
    this.data.name = userStore.userInfo?.name || null
    this.data.phone = userStore.userInfo?.phone || null
    this.data.avatar = userStore.userInfo?.avatar || null
    return this.data
  }

  public async save(data: ModelType) {
    const { code, msg } = await loginApi.doUpdInfo(data)
    if (code !== 0) {
      throw msg
    }
    const userStore = useAppsStore()
    const { doUserInfo } = userStore
    doUserInfo()
  }
}

export default new BaseInfoModel()
